from PyQt5.QtCore import QAbstractListModel , QModelIndex , QVariant , Qt
from PyQt5.QtGui import QBrush , QColor

class MyListModel(QAbstractListModel):                      # 自定义的ListModel
    def __init__(self, parent = ...):
        super().__init__(parent)
        self._data_list = []

    def data(self, index: QModelIndex, role: int = ...):
        """
        继承父类，必须有。设置不同类型调用返回数据
        :param index: 索引
        :param role: 要获取的数据类型
        :return:
        """
        # 设置表格显示使用的数据
        if index.isValid() or (0 <= index.row() < len(self._data_list)):
            if role == Qt.DisplayRole:
                return QVariant(self._data_list[index.row()]['name'])
            elif role == Qt.BackgroundRole:
                if self._data_list[index.row()].id != 0:
                    return QBrush(QColor(84, 255, 159))
                else:
                    return QBrush(QColor(255, 255, 255))
        else:
            return QVariant()

    def rowCount(self, parent: QModelIndex = ...) -> int:
        """
        继承父类，必须有。返回数据总行数
        :param parent:
        :return:
        """
        return len(self._data_list)
    
    def add_item(self, item_data):
        """
        自定义。添加单个数据
        :param item_data: 数据
        :return:
        """
        if item_data:
            self.beginInsertRows(QModelIndex(), len(self._data_list), len(self._data_list) + 1)
            self._data_list.append(item_data)
            self.endInsertRows()

    def delete_item(self, row):
        """
        自定义。删除数据
        :param row: 索引
        :return:
        """
        self.beginRemoveRows(QModelIndex(), row, row - 1)
        del self._data_list[row]
        self.endRemoveRows()
        
    def update_item(self, index, new_item):
        """
        自定义。更新数据
        :param index: 索引
        :param new_item: 新数据
        :return:
        """
        self._data_list[index.row()] = new_item
        self.dataChanged(index, index, Qt.BackgroundRole)

    def clear(self):
        """
        清空数据
        :return:
        """
        self.beginResetModel()
        self._data_list.clear()
        self.endResetModel()
    